package org.windey.client;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.util.ArrayList;

/**
 * 
 * Thread voor de data van de windeyclient te verwerken
 *
 */
public class WindeyClientDataHandler extends Thread
{
	private Robot robot;
	private ArrayList<String> buffer;
	private WindeyClientThreadInterface wcti;
	
	public WindeyClientDataHandler(WindeyClientThreadInterface wcti) throws WindeyClientDataProviderException
	{
		this.wcti = wcti;
		try
		{
			robot = new Robot();
		}
		catch (AWTException e)
		{
			e.printStackTrace();
			throw new WindeyClientDataProviderException();
		}
		buffer = new ArrayList<String>();
	}
	
	/**
	 * 
	 */
	public void run()
	{
		while (wcti.isReceiving())
		{
			try {
				execute(buffer.get(0));
				buffer.remove(0);
			}
			catch (IndexOutOfBoundsException error) {
				
			}
		}
	}

	private void execute(String string)
	{
			try {
				if (!string.equalsIgnoreCase("")) {
					String command = string.split(":")[0] ;
					//System.out.println(command) ;
 					if (command.equalsIgnoreCase("CLICK")) {
						String co = string.split(":")[1] ;
						robot.mouseMove(Integer.parseInt(co.split(",")[0]), Integer.parseInt(co.split(",")[1])) ;
						robot.mousePress(getinput(co.split(",")[2])) ;
						robot.mouseRelease(getinput(co.split(",")[2])) ;
					}
					if (command.equalsIgnoreCase("MOVE")) {
						String co = string.split(":")[1] ;
						robot.mouseMove(Integer.parseInt(co.split(",")[0]), Integer.parseInt(co.split(",")[1])) ;
					}
					if (command.equalsIgnoreCase("KEY")) {
						String co = string.split(":")[1] ;
						//System.out.println("key gedrukt: " + Integer.parseInt(co.split(",")[0]));
						robot.keyPress(Integer.parseInt(co.split(",")[0])) ;
					}
				}
			}
			catch (IndexOutOfBoundsException e) {
				// TODO: handle exception
			}
			catch (NumberFormatException e) {
				
			}
			catch (NullPointerException e) {
				
			}
			catch (IllegalArgumentException e) {
				
			}
    }
	

	private int getinput(String string) {
		int in = Integer.parseInt(string) ;
		int out = 0 ;
		switch (in) {
		case 1: out = 16 ;
				break ;
		case 2: out = 8 ;
				break ;
		case 3: out = 4 ;
				break ;
		case 4: out = 2 ;
				break ;
		}
		return out ;
	}

	/**
	 * 
	 * @param dataLine data die aan de buffer moet worden toegevoegd
	 */
	public void handle(String dataLine)
	{
		buffer.add(dataLine);
	}
}
